package com.yidian.controller.business;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yidian.pojo.order.Order;
import com.yidian.server.order.OrderService;
import com.yidian.server.pay.WeixinPayService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author whb
 * @create 2021-09-15 11:03
 * @desciption 微信支付控制类
 */
@RestController
@RequestMapping("/wxpay")
public class WeixinPayController {
    @Reference
    private OrderService orderService;
    @Reference
    private WeixinPayService weixinPayService;

    /**
     * 生成微信支付二维码
     *
     * @param orderId 订单号
     * @return
     */
    @GetMapping("/createNative")
    public Map createNative(String orderId) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();//获取登录用户名
        Order order = orderService.findById(orderId);//根据订单号查询订单
        if (order != null) {
            if (username.equals(order.getUsername()) && "0".equals(order.getPayStatus()) && "0".equals(order.getOrderStatus())) {
                return weixinPayService.createNative(orderId, order.getPayMoney(), "http://432481v65d.zicp.vip/wxpay/notify.do");//调用生成微信支付二维码的方法
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 支付后的回调方法
     */
    @RequestMapping("/notify")
    public void toNotify(HttpServletRequest request) {
        System.out.println("支付成功后回调..");
        try {
            InputStream inputStream = request.getInputStream();//支付成功后，微信支付平台返回以xml形式的数据流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            //将输入流返回的数据写入到输出流中
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();

            String result = new String(outputStream.toByteArray(), "utf-8");//将返回的xml转化成字符串
            System.out.println(result);

            weixinPayService.notifyLogic(result);//调用回调逻辑
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
